package com.cqvip.innocence.common.util.reflection;


import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName BeanMapUtilByReflect
 * @Description: 对象与map相互转化工具类
 * @Author Innocence
 * @Date 2022/7/6 14:35
 * @Version 1.0
 */
public class BeanMapUtilByReflect {

    /**
     * 对象转map
     *
     * @param object 待转对象
     * @return java.util.Map
     * @author Innocence
     * @date 2022/7/6
     */
    public static Map<String, Object> beanToMap(Object object) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(object));
        }
        return map;
    }

    /**
     * map转对象
     *
     * @param map       待转map
     * @param beanClass 转出类
     * @return T
     * @author Innocence
     * @date 2022/7/6
     */
    public static <T> T mapToBean(Map map, Class<T> beanClass) throws Exception {
        T object = beanClass.newInstance();
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();
            if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                continue;
            }
            field.setAccessible(true);
            if (map.containsKey(field.getName())) {
                field.set(object, map.get(field.getName()));
            }
        }
        return object;
    }
}
